import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import Table from '@knownsec/react-component/dist/Table';
import s from './style.module.css';
import Select, { Option } from '@kuiper-components/select';
import Icon from '../../icon';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import Dialog from '@knownsec/react-component/dist/Dialog';
import fetchFer from 'API/fetch';
import Button from '@kuiper-components/button';
import Pagination from '@knownsec/react-component/dist/Pagination';
import { filterNull } from '../../../../../../common/validation/common';
import { withRouter } from 'react-router';
import { turnToUrlparam } from '../../../../../helpers/getUrlParams';
import EmptyData from '../../../../../components/empty/EmptyData';

const defaultFilter = {
	page: 1,
	limit: 10,
};
function linkDetail({ type, history, id }) {
	const prefilter = new URLSearchParams(location.search).get('filter');
	const filterS = prefilter ? JSON.parse(prefilter) || {} : {};
	const defaultFilter_ = { ...defaultFilter, ...filterS };
	const [tableData, setTableData] = useState({
		data: [],
		count: 0,
	});
	const [filter, setFilter] = useState(defaultFilter_);
	const [dialogShow, setDialogShow] = useState(false);
	const [selRow, setSelRow] = useState({});
	const handleChangeSearch = e => {
		let filter_ = null;
		if (e && e.page) {
			filter_ = filterNull({ ...filter, ...e });
		} else {
			filter_ =
				e === 'r'
					? { ...defaultFilter }
					: filterNull({ ...filter, ...e, ...defaultFilter, page: 1 });
		}
		const backparams = JSON.stringify(filter_);
		const searchString = 'filter=' + encodeURI(backparams);
		setFilter(filter_);
		console.log('[ filter_ ]-543', filter_);
		history.replace(
			`/job-manage/ipv6-monitor/linkDetail/${id}/${type}?${searchString}`
		);
	};
	const columns = [
		{
			title: 'URL地址',
			dataIndex: 'url',
			className: s.width300,
			key: 'url',
			render(e, row) {
				return (
					<Tooltip
						overlay={
							<div>
								<p>{e}</p>
								<p>上级页面:{row.referer}</p>
							</div>
						}
						placement={'top'}
					>
						<div className={s.target}>
							<p>{e}</p>
							<p className={s.up}>上级页面:{row.referer}</p>
						</div>
					</Tooltip>
				);
			},
		},
		{
			title: '检测结果',
			dataIndex: 'is_normal',
			key: 'is_normal',
			render(e) {
				const dom = e ? (
					<p className={s.linkType}>
						<Icon active={5} />
						<span>可访问</span>
					</p>
				) : (
					<p className={s.linkType}>
						<Icon active={6} />
						<span>不可访问</span>
					</p>
				);
				return dom;
			},
		},
		{
			title: '状态码',
			dataIndex: 'status_code',
			key: 'status_code',
		},
		{
			title: '类型',
			dataIndex: 'is_foreign_link',
			key: 'is_foreign_link',
			render(e) {
				const dom = e ? (
					<p className={s.linkType}>
						<Icon active={10} />
						<span>外链</span>
					</p>
				) : (
					<p className={s.linkType}>
						<Icon active={9} />
						<span>内链</span>
					</p>
				);
				return dom;
			},
		},
		{
			title: '链接类型',
			dataIndex: 'url_type',
			key: 'url_type',
		},
		{
			title: '操作',
			dataIndex: 'affects',
			key: 'affects',
			className: s.width100,
			render(e, row) {
				return (
					<span
						className={s.active}
						onClick={() => {
							setDialogShow(true);
							const row_ = { ...row };
							Object.keys(row.request_headers)[0] &&
								(row_.request = row.request_headers);
							Object.keys(row.response_headers)[0] &&
								(row_.response = row.response_headers);
							setSelRow(row_);
						}}
					>
						查看
					</span>
				);
			},
		},
	];
	const getData = async () => {
		const filter_ = { ...filter, task_session_id: id, depth: type };
		const params = turnToUrlparam(filter_);
		const res = await fetchFer(
			`/api/v2/repodatas/ipv6/support_check/detail?${params}`,
			{
				method: 'GET',
				checkStatus: 501,
			}
		).catch(error => {
			console.log('[ error ]-222', error);
			return {};
		});
		console.log('[  ]-151', res);
		setTableData({ data: res.results?.data, count: res.results?.total });
	};
	useEffect(() => {
		getData();
	}, [filter]);
	return (
		<div className={s.content}>
			<div className={s.toolBox}>
				<div>
					<Select
						placeholder="检测结果"
						className={s.item}
						value={filter.status}
						getPopupContainer={triggerNode => triggerNode}
						onChange={status => {
							handleChangeSearch({ status });
						}}
					>
						<Option value="1">可访问</Option>
						<Option value="2">不可访问</Option>
					</Select>
					<Select
						placeholder="类型"
						className={s.item}
						value={filter.url_type}
						getPopupContainer={triggerNode => triggerNode}
						onChange={url_type => {
							handleChangeSearch({ url_type });
						}}
					>
						<Option value="1">内链</Option>
						<Option value="2">外链</Option>
					</Select>
					<Button
						className={s.btn}
						onClick={() => {
							handleChangeSearch('r');
						}}
					>
						重置
					</Button>
				</div>
			</div>
			<Table
				className={s.newtable}
				// pro
				columns={columns}
				data={tableData.data}
				empty={<EmptyData type={'img'} className={s.nobor} />}
			/>
			<div className={s.Pagination}>
				{tableData.count > 10 && (
					<Pagination
						current={filter.page || 1}
						pageSize={filter.limit || 10}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						total={tableData.count}
						onChange={(page, limit) => {
							handleChangeSearch({ page, limit });
						}}
					/>
				)}
			</div>
			<Dialog
				visible={dialogShow}
				onhide={() => {
					setDialogShow(false);
				}}
				title="快照详情"
				cancelText="取消"
				getPopupContainer={triggerNode => triggerNode}
				confirmText="确定"
				className={cn(s.w800)}
			>
				<div className={cn(s.p20)}>
					<p className={s.dialogP}>
						<span className={s.titleKey}>URL地址：</span>
						<span>{selRow.url}</span>
					</p>
					<p className={s.dialogP}>
						<span className={s.titleKey}>上级页面：</span>
						<span>{selRow.referer}</span>
					</p>
					<p>
						<span className={s.titleKey}>状态码：</span>
						{!isNaN(selRow.status_code) ? selRow.status_code : '- -'}
					</p>
					<p>
						<span className={s.titleKey}>类型：</span>
						<Icon active={selRow.is_foreign_link ? 10 : 9} />
						{selRow.is_foreign_link ? '外链' : '内链'}
					</p>
					<p>
						<span className={s.titleKey}>链接层级：</span>
						{selRow.depth === 2 ? '二级链接' : '三级链接'}
					</p>
					<p>
						<span className={s.titleKey}>链接类型：</span>
						{selRow.url_type || '- -'}
					</p>
					<p>
						<span className={s.titleKey}>IP：</span>
						{selRow.ip || '- -'}
					</p>
					<p>
						<span className={s.titleKey}>检测结果：</span>
						<Icon active={selRow.is_normal ? 5 : 6} />
						{selRow.is_normal ? '可访问' : '不可访问'}
					</p>
					<div>
						<span className={s.titleKey}>快照详情：</span>
						{selRow.request || selRow.response ? (
							<div>
								<div className={s.Snapshot}>
									{Object.entries(selRow.request).map(([k, v], i) => {
										return (
											<p key={i} className={s.Snapshot_p}>
												<span>{k}</span>:<span>{v}</span>
											</p>
										);
									})}
									{Object.entries(selRow.response).map(([k, v], i) => {
										return (
											<p
												key={i}
												className={cn(s.Snapshot_p, i === 0 && s.Snapshot_0)}
											>
												<span>{k}</span>:<span>{v}</span>
											</p>
										);
									})}
								</div>
							</div>
						) : (
							'- -'
						)}
					</div>
				</div>
			</Dialog>
		</div>
	);
}

linkDetail.propTypes = {
	type: PropTypes.string,
	history: PropTypes.any,
	id: PropTypes.any,
};
export default withRouter(linkDetail);
